package com.hankol.community.fragment

import android.annotation.SuppressLint
import android.graphics.Rect
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.widget.PopupWindow
import android.widget.SeekBar
import androidx.lifecycle.Observer
import com.baselibrary.BaseConstant
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.bean.OnActResultBean
import com.baselibrary.bean.TimelineInfoData
import com.baselibrary.extension.checkNotNull
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.utils.EventBusUtils.sendNotifyParams
import com.baselibrary.view.share.SharePopupWindow
import com.okhttp.comment.CommentBean
import com.baselibrary.activity.BaseActivity
import com.baselibrary.activity.BaseFragment
import com.hankol.community.R
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.databinding.FragmentVideoPageBinding
import com.hankol.community.databinding.PopupCommentlistBinding
import com.hankol.community.viewmodel.VideoPageViewModel
import com.like.LikeButton
import com.like.OnLikeListener
import com.okhttp.comment.BaseCommentAdapter
import com.okhttp.comment.CommentConstant
import com.okhttp.comment.CommentReplyBean
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.tencent.rtmp.TXVodPlayer
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


/** 首页-- 视频 页
 * @description 新版视频 页
 */
class VideoPageFragment( var mVideoId: Int) : BaseFragment(), View.OnClickListener, OnRefreshLoadMoreListener, VideoPageViewModel.OnPublishCompleteListener {
    private lateinit var mBinding: FragmentVideoPageBinding
    private lateinit var mViewModel: VideoPageViewModel
    private lateinit var mVodPlayer: TXVodPlayer
    private var mPage = 1
    private var mSlidePro: Int = 0
    private var userId: Int = 0
    private var isDoubleClick = false
    private var mNetErrorView: View? = null
    var index = -1
    var data: TimelineInfoData.ClientTimeline? = null
    private var mPopupBinding: PopupCommentlistBinding? = null
    private var mCommentBean: CommentBean.DataBean? = null
    private var mCommentPopup: PopupWindow? = null
    private var mNetErrorViewPopup: PopupWindow? = null
    private var mSharePopupWindow: SharePopupWindow? = null
    private var playSpeedList = mutableListOf<String>()
    private val tHandler = Handler { msg: Message ->
        when (msg.what) {
            mViewModel.UP_PLAYER -> mBinding.ivDetailsPlay.visibility = View.GONE
        }
        false
    }
    val communityHelp: CommunityHelp = ActivityRouter.getARouterInterface(ActivityRouter.COMMUNITY.COMMUNITY_HELP)

    companion object {
        fun newInstance(mVideoId: Int): VideoPageFragment {
            return VideoPageFragment(mVideoId)
        }
    }

    override fun init() {
        StatusBarUtil.setStatusBarDarkTheme(attachActivity, false)
        SpUtils.putBoolean(requireContext(), Constants.KEY_CURRENT_IS_VIDEO_PAGE, true)
        playSpeedList.add("1.0x")
        playSpeedList.add("1.5x")
        playSpeedList.add("2.0x")
        playSpeedList.add("0.5x")
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        mVodPlayer = TXVodPlayer(context)
        mBinding = getDataBinding<FragmentVideoPageBinding>()
        mViewModel = getFragmentViewModelProvider(this).get(VideoPageViewModel::class.java)
//        setStatusBarHeight(mBinding.statusBar)
        initObserve()
        loadData()
        initListener()
        EventBusUtils.sendNotify1Value(MessageBus.msgId_current_playing_video_page, true)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_video_page
    }

    @SuppressLint("ClickableViewAccessibility") private fun initListener() {
        mBinding.llDetailsLike.setOnClickListener(this)
        mBinding.ivDetailsHead.setOnClickListener(this)
        mBinding.llDetailsShare.setOnClickListener(this)
        mBinding.tvDetailsTopic.setOnClickListener(this)
        mBinding.ivDetailsFollow.setOnClickListener(this)
        mBinding.tvDetailsComment.setOnClickListener(this)
        mBinding.rlDetailsComment.setOnClickListener(this)
        mBinding.tvDetailsPlaySpeed.setOnClickListener(this)
        mBinding.ivDetailsFullscreen.setOnClickListener(this)

        mBinding.sbDetailsDpeed.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, p1: Int, p2: Boolean) {
                mSlidePro = seekBar.progress
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {
            }

            override fun onStopTrackingTouch(p0: SeekBar?) {
                //手指抬起获取当前SeekBar进度
                mVodPlayer.seek(mSlidePro / 1000)
                mVodPlayer.resume()
            }

        })
        mBinding.tlDetailsDoubleclick.setOnDownClickListener { isLike ->
            if (!isLike) { //控制是点赞还是暂停
                mBinding.ivDetailsPlay.visibility = if (mBinding.ivDetailsPlay.isShown) View.GONE else View.VISIBLE
                if (mBinding.ivDetailsPlay.isShown) {
                    mViewModel.hidePlayerView(tHandler)
                }
            } else {
                if (!isDoubleClick) {
                    //双击屏幕 判定为点赞
                    mViewModel.reqSupport(true, 4, mVideoId)
                }
            }
        }
        mBinding.llDetailsDpeed.setOnTouchListener(object : OnTouchListener {
            @SuppressLint("ClickableViewAccessibility")
            override fun onTouch(p0: View, event: MotionEvent): Boolean {
                val seekRect = Rect()
                mBinding.sbDetailsDpeed.getHitRect(seekRect)

                if (event.y >= seekRect.top - 50 && event.y <= seekRect.bottom + 50) {
                    val y = (seekRect.top + seekRect.height() / 2).toFloat()
                    var x: Float = event.x - seekRect.left
                    if (x < 0) {
                        x = 0f
                    } else if (x > seekRect.width()) {
                        x = seekRect.width().toFloat()
                    }
                    val me = MotionEvent.obtain(event.downTime, event.eventTime, event.action, x, y, event.metaState)
                    return mBinding.sbDetailsDpeed.onTouchEvent(me)
                }
                return false

            }
        })
        mBinding.ivDetailsGive.setOnLikeListener(object : OnLikeListener {
            override fun liked(likeButton: LikeButton?) {
                //点赞
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                mBinding.ivDetailsGive.isEnabled = false
                mViewModel.reqSupport(true, 4, mVideoId)
            }

            override fun unLiked(likeButton: LikeButton?) {
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                mBinding.ivDetailsGive.isEnabled = false
                //取消点赞
                mViewModel.reqSupport(false, 4, mVideoId)
            }
        })

        mBinding.ivDetailsCollection.setOnLikeListener(object : OnLikeListener {
            override fun liked(likeButton: LikeButton?) {

                //收藏
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                // 进行点击事件后的逻辑操作
                mBinding.ivDetailsCollection.isEnabled = false
                mViewModel.reqCollection(true, 4, mVideoId.toLong())
            }

            override fun unLiked(likeButton: LikeButton?) {
                //取消收藏
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                mBinding.ivDetailsCollection.isEnabled = false
                // 进行点击事件后的逻辑操作
                mViewModel.reqCollection(false, 4, mVideoId.toLong())
            }
        })
    }

    @SuppressLint("NotifyDataSetChanged") private fun initObserve() {
        mViewModel.dynamicVideoLiveData.observe(this, Observer {
            if (it != null) {
                data = it
                userId = it.user.id
                isDoubleClick = it.isSupported
//                if (index == 0) mActivity.setCollectionData(it.isFavorited)//设置赞属性
                mViewModel.setViewOut(mBinding, it, tHandler, mVodPlayer, requireActivity(), this)
            } else {
                mBinding.llTools.visibility=View.GONE
                if (mNetErrorView == null) {
                    mNetErrorView = layoutInflater.inflate(R.layout.popup_neterror_revision, null)
                }
                mNetErrorView?.let {
                    mNetErrorViewPopup = communityHelp.showCommentPop(requireActivity(), it, mBinding.llBottom, Gravity.CENTER)
                }
            }
            mBinding.ivDetailsInterval.post { mBinding.tvDetailsName.maxWidth = mViewModel.setNameTVMaxWidthOut(requireActivity(), mBinding) }

        })
        mViewModel.commentListLiveData.observe(this, Observer {
            mPopupBinding?.smartComment?.finishRefresh()
            mPopupBinding?.smartComment?.finishLoadMore()
            if (it != null) {
                mCommentBean = it
                mPopupBinding?.PBarSldComment?.visibility = View.GONE
                mPopupBinding?.BaseCommentView?.visibility = View.VISIBLE
                mPopupBinding?.BaseCommentView?.commentNetData(it, mPage)
                mPopupBinding?.tvVideoCommentHead?.text = "共${it.totalCount}条评论"
                mPage++
            }
        })
        mViewModel.followLiveData.observe(this, Observer {
            if (it.flag) {
                data?.apply {
                    user.isFocusFans = !user.isFocusFans
                    mBinding.ivDetailsFollow.isSelected = user.isFocusFans
                    com.hankol.message.HKIMUtils.followSendMsg(user.id.toInt(), it.friendState)
                }
            }
        })
        mViewModel.collectionLiveData.observe(this, Observer {
            if (it) mViewModel.upCollectionStateOut(data, mBinding)
            data?.apply {
//                if (index == 0) mActivity.setCollectionData(isFavorited)
            }
        })
        mViewModel.supportLiveData.observe(this, Observer {
            if (it) isDoubleClick = mViewModel.upSupportedStateOut(data, mBinding)

        })
        mViewModel.friendLiveData.observe(this, Observer {
            mSharePopupWindow?.setShareFriendAdapter(mViewModel.changeFriend(it))
        })
        mViewModel.shareAddNumLD.observe(this, Observer {
            data?.let {
                it.forwardNum = it.forwardNum + 1
                mBinding.tvDetailsShare.text = NumberUtils.formatBigNum((it.forwardNum + it.outForwardNum).toString())
            }
        })
    }

    private fun loadData() {
        mViewModel.reqVideoHistoryAdd(mVideoId.toLong())
        mViewModel.reqDynamicVideoDetails(mVideoId.toLong())
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.tv_details_topic -> data?.apply {
                if (tagIds.checkNotNull()) {
                    val hashMap = HashMap<String, Any>()
                    hashMap["tid"] = tagIds[0]
                    hashMap["tsource"] = "动态内部"
                    ARouterUtils.jump(ActivityRouter.COMMUNITY.COMMUNITY_TOPIC_DETAIL, hashMap)
                }
            }

            R.id.back, R.id.tv_neterror_other -> {
                val builder = MessageBus.Builder()
                val messageBus = builder.codeType(MessageBus.msgId_back_close).build()
                EventBus.getDefault().post(messageBus)
            }
            R.id.iv_details_head -> {
                data?.apply {
                    val hashMap = HashMap<String, Any>()
                    hashMap[BaseConstant.USER_ID] = user.id.toString()
                    ARouterUtils.jump(ActivityRouter.MINE_CENTER.USER_INFO, hashMap)
                }
            }
            R.id.iv_details_follow -> {
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                data?.apply {
                    if (!user.isFocusFans) {
                        //详情界面只能去关注，不能取消关注。因此false时才执行事件
                        mViewModel.reqFollow(requireActivity(), true, 1, user.id)
                        mViewModel.sensorsFollow(SpUtils.getInstance().loadUserBean, user)
                    }
                }
            }
            R.id.ll_details_share -> {
                if (DoubleClickHelper.isOnDoubleClick()) return
                data?.let {
                    mSharePopupWindow = mViewModel.share(it, requireActivity() as BaseActivity, communityHelp)
                    mViewModel.reqFriendList()
                }
            }
            R.id.rl_details_comment -> {
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                if (DoubleClickHelper.isOnDoubleClick()) return
                //打开评论
                showCommentPop()
            }
            R.id.ll_base_comment_empty -> {
                if (DoubleClickHelper.isOnDoubleClick()) return
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                data?.apply {
                    if (user != null) {
                        //埋点
                        BaseConstant.loadCommentEventBusBean("动态", "内容详情页")
                        communityHelp.openCommentActivity(
                            requireActivity(), 6, mVideoId, mBinding.tvDetailsComment.text.toString().trim(), user.name, false, CommentConstant.COMMENT_REQUESTCODE
                        )
                    }

                }
            }
            R.id.tv_popup_content, R.id.ll_popup_content -> {
                if (DoubleUtils.isFastDoubleClick()) {
                    return
                }
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                mCommentPopup?.dismiss()
                data?.apply {
                    if (user != null) {
                        communityHelp.openCommentActivity(
                            requireActivity(), 6, mVideoId, mBinding.tvDetailsComment.text.toString().trim(), user.name, false, CommentConstant.COMMENT_REQUESTCODE
                        )
                    }
                }
            }

            R.id.tv_popup_send -> {
                KeyBoardUtils.hideShowKeyboard(requireContext())
                mPopupBinding?.let {
                    mViewModel.addComment(6, mVideoId, it.tvPopupContent, requireActivity(), this)
                }
            }
            R.id.tv_neterror_again -> {
                loadData()
                mNetErrorViewPopup?.let {
                    if (it.isShowing) it.dismiss()
                }
            }
            /* R.id.iv_details_fullscreen -> {
                 if (mBinding.ivDetailsFullscreen.isSelected) {
                     //退出全屏
                     mBinding.llTools.visibility = View.VISIBLE
                     mBinding.llVideoIntroduce.visibility = View.VISIBLE
                     mBinding.ivDetailsFullscreen.isSelected = false
                     mBinding.ivDetailsFullscreen.setImageResource(R.drawable.ic_video_fullscreen)
                 } else {
                     //全屏幕
                     mBinding.llTools.visibility = View.GONE
                     mBinding.llVideoIntroduce.visibility = View.GONE
                     mBinding.ivDetailsFullscreen.isSelected = true
                     mBinding.ivDetailsFullscreen.setImageResource(R.drawable.ic_video_smallscreen)
                 }
             }*/
            /*R.id.tv_details_playSpeed -> {
                when (mBinding.tvDetailsPlaySpeed.text.toString()) {
                    //当为 1.0x速度被点击的时候，触发下一个倍速。
                    playSpeedList[0] -> {
                        mBinding.tvDetailsPlaySpeed.text = playSpeedList[1]
                        mVodPlayer.setRate(1.5F)
                    }
                    playSpeedList[1] -> {
                        mBinding.tvDetailsPlaySpeed.text = playSpeedList[2]
                        mVodPlayer.setRate(2.0F)
                    }
                    playSpeedList[2] -> {
                        mBinding.tvDetailsPlaySpeed.text = playSpeedList[3]
                        mVodPlayer.setRate(0.5F)
                    }
                    playSpeedList[3] -> {
                        mBinding.tvDetailsPlaySpeed.text = playSpeedList[0]
                        mVodPlayer.setRate(1.0F)
                    }
                }
            }*/
        }
    }

    private fun showCommentPop() {
        if (mPopupBinding == null) {
            mPopupBinding = mViewModel.openCommentViewOut(this, this)
            if (mCommentPopup == null) {
                mViewModel.reqCommentList(mPage, mVideoId.toLong(), 0)
                mCommentPopup = communityHelp.showCommentPop(requireActivity(), mPopupBinding!!.root, mBinding.llBottom, Gravity.BOTTOM)
            }
        }
        mCommentPopup?.showAtLocation(mBinding.llBottom, Gravity.BOTTOM, 0, 0)
        communityHelp.setBackgroundAlpha(requireActivity())
    }
    var currentVideoId=""
    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_follow_and_cancel) {
            mViewModel.reqDynamicVideoDetails(mVideoId.toLong())
        } else if (messageBus.codeType == MessageBus.msgId_share_success) {
            data?.let {
                mViewModel.reqAddShareNum(it.id)
            }
        } else if (messageBus.codeType == MessageBus.msgId_video_page_pause_video_play) {
            val isPasue = messageBus.param1 as Boolean
            val currentVideoId = messageBus.param2 as String
            if (isPasue) {
                mVodPlayer.pause()
                mBinding.ivDetailsPlay.isSelected = false
            } else {
                if ("${mVideoId}".equals(currentVideoId)) {
                    mVodPlayer.resume()
                    mBinding.ivDetailsPlay.isSelected = true
                    EventBusUtils.sendNotify1Value(MessageBus.msgId_current_playing_video_page, true)
                }
            }
        } else if (messageBus.codeType == MessageBus.msgid_video_page_comment_result) {
            if(!currentVideoId.equals("${mVideoId}")){
                return
            }
            val resultBean = messageBus.message as OnActResultBean
            var requestCode = resultBean.requestCode
            var resultCode = resultBean.resultCode
            var data = resultBean.data
            mPopupBinding?.let {
                it.BaseCommentView.commentOnResult(requestCode, resultCode, data)
                it.BaseCommentView.setSayContent(requestCode, resultCode, data, mBinding.tvDetailsComment, CommentConstant.COMMENT_DEF_CONTENT_VERSION_2)
                val mCommentNum: Int = it.BaseCommentView.upCommentNum(requestCode, resultCode, data, this.data!!.commentNum, mBinding.tvDetailsCommentNum)
                if (mCommentNum != -1) {
                    it.tvVideoCommentHead.text = "共${mCommentNum}条评论"
                    this.data!!.commentNum = mCommentNum
                    sendNotifyParams(MessageBus.msgid_comment_succ, mCommentNum, this.data!!.id, null, null, null, null, null, null)
                }
                if (requestCode == CommentConstant.COMMENT_REQUESTCODE && resultCode == CommentConstant.COMMENT_RESPONSE) {
                    showCommentPop()
                    it.BaseCommentView.setSayContent(requestCode, resultCode, data, it.tvPopupContent, CommentConstant.COMMENT_DEF_CONTENT_VERSION_1)
                    it.tvPopupSend.isSelected = data != null && !TextUtils.isEmpty(data.getStringExtra(CommentConstant.COMMENT_CONTENT))
                    it.tvPopupSend.isEnabled = data != null && !TextUtils.isEmpty(data.getStringExtra(CommentConstant.COMMENT_CONTENT))
                }
                if (requestCode == CommentConstant.REQUESTCODE && this.data != null) { //Activity的
                    mBinding.tvDetailsCommentNum.text = (this.data!!.commentNum + 1).toString()
                    this.data!!.commentNum = this.data!!.commentNum + 1
                    sendNotifyParams(MessageBus.msgid_comment_succ, this.data!!.commentNum, this.data!!.id, null, null, null, null, null, null)
                }
            }
        } else if (messageBus.codeType == MessageBus.msgId_video_page_switch_offset) {//翻页
            val offset = messageBus.param1 as Float
              currentVideoId = messageBus.param2 as String
            HKLogUtils.e("准备播放：${currentVideoId}------${mVideoId}")
            if ("${mVideoId}".equals(currentVideoId)) {
                if (offset != 0f) {
                    if (!DoubleClickHelper.isOnDoubleClick()) {
                        //暂停
                        mVodPlayer.pause()
                        mBinding.ivDetailsPlay.isSelected = false
                    }
                } else {
                    //播放
                    mVodPlayer.resume()
                    mBinding.ivDetailsPlay.isSelected = true
                }
            }
        } else if (messageBus.codeType == MessageBus.msgId_current_playing_video_page) {//
            //当前页面是视频页播放
            val isBlack = messageBus.param1 as Boolean
            isCurrentShow = isBlack
        } else if (messageBus.codeType == MessageBus.msgId_video_page_refresh) {//
            mVodPlayer.stopPlay(true)
            mVodPlayer.setVodListener(null)
        }
    }

    //视频页是否当前正在显示
    var isCurrentShow = false;
    override fun onResume() {
        super.onResume()
        val currentIsVideoPage = SpUtils.getBoolean(requireContext(), Constants.KEY_CURRENT_IS_VIDEO_PAGE, false)
        if (currentIsVideoPage && !mVodPlayer.isPlaying) {
            mVodPlayer.resume()
            mBinding.ivDetailsPlay.isSelected = true
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) { //隐藏
            if (mVodPlayer.isPlaying) {
                mVodPlayer.pause()
                mBinding.ivDetailsPlay.isSelected = false
            }
        }
    }

    override fun onPause() {
        mViewModel.hidePlayerView(tHandler)
        mVodPlayer.pause()
        mBinding.ivDetailsPlay.isSelected = false
        super.onPause()
    }

    override fun onStop() {
//        if (mVodPlayer.isPlaying) {
        mVodPlayer.pause()
        mBinding.ivDetailsPlay.isSelected = false
//        }
        super.onStop()
    }

    override fun onDestroyView() {
        mVodPlayer.pause()
        mVodPlayer.stopPlay(true)
        mVodPlayer.setVodListener(null)
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroyView()
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        //评论刷新
        mPage = 1
        mViewModel.reqCommentList(mPage, mVideoId.toLong(), 0)
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        //评论加载
        mPopupBinding?.let {
            val commentNorMarAdapter: BaseCommentAdapter = it.BaseCommentView.commentAdapterType
            if (mCommentBean?.count == commentNorMarAdapter.itemCount) {
                it.smartComment.finishRefresh()
                it.smartComment.finishLoadMore()
                ToastUtils.showShort(context, "已经全部加载完成")
                return
            }
            mViewModel.reqCommentList(mPage, mVideoId.toLong(), 0)
        }
    }

    /**
     * 发布成功
     */
    override fun onPublishComplete(bean: CommentReplyBean) {
        mBinding.tvDetailsComment.text = CommentConstant.COMMENT_DEF_CONTENT_VERSION_2
        mPopupBinding?.let {
            it.tvPopupSend.isSelected = false
            it.tvPopupSend.isEnabled = false
            it.tvPopupContent.text = CommentConstant.COMMENT_DEF_CONTENT_VERSION_2
        }
        mPopupBinding?.let {
            it.BaseCommentView.commentOnResult(bean)
        }
    }

}